const app = getApp()

Page({
  data: {
    longitude: 0,
    latitude: 0,
    markers: []
  },

  onLoad() {
    this.map = wx.createMapContext('map')
  },

  onShow() {
    this.loadData()
  },

  onReady() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        let {
          longitude,
          latitude
        } = res

        this.setData({
          longitude,
          latitude
        })
      }
    })

    this.loadData()
  },

  loadData() {
    app.minipet.get({
      success: (res) => {
        const markers = res.data.map(value => {
          let {
            _id,
            latitude,
            longitude,
            message,
            type
          } = value

          return {
            id: _id,
            latitude,
            longitude,
            title: message,
            iconPath: `/resources/${type}.png`,
            width: 40,
            height: 40
          }
        })

        this.setData({
          markers
        })
      }
    })
  },

  handleLocationTap() {
    this.map.moveToLocation()
  },

  handlePublishTap() {
    wx.navigateTo({
      url: '/pages/publish/publish',
    })
  },

  handleMarkerTap(e) {
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + e.markerId,
    })
  }
})